package com.example.zrdemo1.controller;

import com.example.zrdemo1.pojo.User;
import com.example.zrdemo1.service.UserService;
import com.example.zrdemo1.utils.DateInfo;
import com.example.zrdemo1.utils.GetQRCode;
import com.example.zrdemo1.utils.IpInfo;
import com.example.zrdemo1.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/love")
public class UserController {
    @Value("${baseUrl}")
    private String baseUrl;
    @Value("${redisValidDay}")
    private  Integer redisValidDay;
    @Autowired
    private UserService userService;

    private  Boolean isOpen=true;

    @Autowired
    private RedisTemplate redisTemplate;

//    @ResponseBody
    @PostMapping("/addUser")
    public String insertUser(User user,HttpServletRequest request){




        String preUuid = UUID.randomUUID().toString().replace("-","");
//        获取ip地址
        user.setIpAdrr(IpInfo.getIpAddr(request));

        User conditionUser=new User();
        conditionUser.setVx(user.getVx());
        conditionUser.setUserName(user.getUserName());
// 重复则跳
            if(userService.findUser(conditionUser)>0){
                return "insertmistake";
            }
            else {
                userService.insertUser(user);
                redisTemplate.opsForValue().set(preUuid,DateInfo.getTime(),redisValidDay, TimeUnit.DAYS);
            }


        // 填写完成跳转
       String  jumpUrl= String.format("redirect:%s?passkey=%s&active=%s",baseUrl+"getChooseSexForm",preUuid,user.getUid());
        return jumpUrl;

    }

    @ResponseBody
    @GetMapping("/showOwnInfo")
    public JsonResult<User> selectOwnUserInfo(@RequestParam(value = "token",required = true) String token){

            User user = userService.selectOwnInfo(token);
            return new JsonResult<User>(BaseController.OK,user);
    }


    @ResponseBody
    @PostMapping("/updateInfo")
    public JsonResult<Void> updateUserInfo(@RequestBody User user){

        userService.updateUserInfo(user);
        return new JsonResult<>(BaseController.OK);
    }

    @ResponseBody
    @PostMapping("/showOtherInfo")
    public JsonResult<User> selectOtherUserInfo(@RequestBody String token){

     //   userService.selectOtherUserInfo()
        User user = userService.selectOtherUserInfo(token);

        return new JsonResult<User>(BaseController.OK,user);
    }

    /**
     * 下面的控制器都是归属于校园线下月老系列
     */

    /**
     * 扫描二维码后 请求该控制器
     * 根据sex随机返回一个异性的个人资料
     * @param sex 性别
     * @return
     */
  //  @ResponseBody
    @GetMapping("/showOtherInfoTwo/{sex}")
    public String selectOtherUserInfoTwo(HttpServletRequest  httpServletRequest,Integer active,@PathVariable("sex") String sex,String passkey,Integer friend,ModelMap modelMap){

        if(passkey==null||redisTemplate.opsForValue().get(passkey)==null){

            return "error";
        }
        else {
            redisTemplate.delete(passkey);
        }


//        User user = userService.selectOtherUserInfoTwo(sex);

        User user = userService.findRandomLove(sex,active,httpServletRequest);

        modelMap.addAttribute("user",user);

        if(friend!=null){
            return "friendinfo";
        }
        else {   return "info";

        }

      //  return new JsonResult<User>(BaseController.OK,user);
    }



    /**
     * 根据获取异性信息请求URL自动生成二维码
     * @param request
     * @param session
     */
    @ResponseBody
    @GetMapping("/getQRCodeFromUrl/{sex}")
    public void getUserInfoAutoQRCode(HttpServletRequest request, String passkey, HttpServletResponse response, HttpSession session, @PathVariable("sex") String sex){


        String url = baseUrl+"showOtherInfoTwo/" + sex+"?passkey="+passkey;
        int width = 400;
        int height = 400;
        System.err.println(url);
        //生成二维码 并设置该二维码的属性 保存成输出流
        ByteArrayOutputStream out = GetQRCode.getQRCodeByteArrayStream(url,width,height);


        //设置响应内容的类型和大小
        response.setContentType("image/png");
        response.setContentLength(out.size());

        //获得响应的输出流并把二维码流写入
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @GetMapping("/del")
    @ResponseBody
    public String delById(Integer id){
        userService.del(id);
        return "successss";
    }

    @GetMapping("/getalluser")
    public String findallandshow(ModelMap modelMap){
        List<User> all = userService.getAll();
        modelMap.addAttribute("listuser",all);
        return "findall";
    }
    @GetMapping("/insertform")
    public String getInsertForm(){

        return "insert";
    }

    @GetMapping("/insertfriendform")
    public String getInsertFriendForm(){

        return "friendinsert";
    }
  /*


    friend 添加
   */
    @PostMapping("/addUserFriend")
    public String insertUserFriend(User user,HttpServletRequest request){


        user.setIsdeleted(2);

        String preUuid = UUID.randomUUID().toString().replace("-","");
//        获取ip地址
        user.setIpAdrr(IpInfo.getIpAddr(request));

        User conditionUser=new User();
        conditionUser.setVx(user.getVx());
        conditionUser.setUserName(user.getUserName());
// 重复则跳
        if(userService.findUser(conditionUser)>0){
            return "insertmistake";
        }
        else {
            userService.insertUser(user);
            redisTemplate.opsForValue().set(preUuid,DateInfo.getTime(),redisValidDay, TimeUnit.DAYS);
        }


        // 填写完成跳转  friend =1 则为friend
        String  jumpUrl= String.format("redirect:%s?passkey=%s&active=%s&friend=1",baseUrl+"getChooseSexForm",preUuid,user.getUid());
        return jumpUrl;

    }
    /**
     * 获取表单页面的二维码
     * @param request
     * @param response
     * @param session
     */

    @GetMapping("/getFormQRCode")
    public void getFormQRCode(HttpServletRequest request, HttpServletResponse response, HttpSession session){

        String url = baseUrl+"insertform/";
        int width = 400;
        int height = 400;
        System.err.println(url);
        //生成二维码 并设置该二维码的属性 保存成输出流
        ByteArrayOutputStream out = GetQRCode.getQRCodeByteArrayStream(url,width,height);


        //设置响应内容的类型和大小
        response.setContentType("image/png");
        response.setContentLength(out.size());

        //获得响应的输出流并把二维码流写入
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取表单页面的二维码
     * @param request
     * @param response
     * @param session
     */
    @GetMapping("/getFriendFormQRCode")
    public void getFriendFormQRCode(HttpServletRequest request, HttpServletResponse response, HttpSession session){

        String url = baseUrl+"insertfriendform/";
        int width = 400;
        int height = 400;
        System.err.println(url);
        //生成二维码 并设置该二维码的属性 保存成输出流
        ByteArrayOutputStream out = GetQRCode.getQRCodeByteArrayStream(url,width,height);


        //设置响应内容的类型和大小
        response.setContentType("image/png");
        response.setContentLength(out.size());

        //获得响应的输出流并把二维码流写入
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 视图解析后跳转到性别选择页面
     * @return
     */
    @GetMapping("/getChooseSexForm")
    public String getChooseSexForm(){

        return "choosebydog";
    }

    /**
     * 获取选择性别页面的二维码
     * @param request
     * @param response
     * @param session
     */
    @GetMapping("/getChooseSexFormQRCode")
    public void getChooseSexFormQRCode(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        String url = baseUrl+"getChooseSexForm/";
        String preUuid = UUID.randomUUID().toString().replace("-","");
        url=url+"?passkey="+preUuid;
//        写入key

        redisTemplate.opsForValue().set(preUuid,DateInfo.getTime(),redisValidDay, TimeUnit.DAYS);
        System.out.println(url);
        int width = 400;
        int height = 400;

        //生成二维码 并设置该二维码的属性 保存成输出流
        System.out.println(request.getRemoteAddr());
        ByteArrayOutputStream out = GetQRCode.getQRCodeByteArrayStream(url,width,height);


        //设置响应内容的类型和大小
        response.setContentType("image/png");
        response.setContentLength(out.size());

        //获得响应的输出流并把二维码流写入
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
